import Footer from './footer/footer'
import Header from './header/header'
import { Outlet } from 'react-router-dom'
import { styled } from '@mui/material'
import { Alert } from './alert'
import { useEffect } from 'react'
import { useAppDispatch, useAppSelector } from '../../store/hooks'
import { fetchAllProducts } from '../../store/reducers/slices/allProductsSlice'
import { selectAccessToken } from '../../store/reducers/selectors'
import { withProtection } from '../../hoc/withProtection'
import { loadingSlice } from '../../store/reducers/slices/loadingSlice'

const StyledContainer = styled('div')(() => ({
	display: 'flex',
	width: '100%',
	alignItems: 'flex-start',
	justifyContent: 'center',
	minHeight: 'calc(100vh - 289px)',
}))

const Root = withProtection(() => {
	const accessToken = useAppSelector(selectAccessToken)
	const dispatch = useAppDispatch()

	useEffect(() => {
		if (accessToken) {
			dispatch(loadingSlice.actions.setLoading(true))
			dispatch(fetchAllProducts()).then(() =>
				dispatch(loadingSlice.actions.setLoading(false))
			)
		}
	}, [dispatch, accessToken])

	return (
		<>
			<Header />
			<Alert />
			<StyledContainer>
				<Outlet />
			</StyledContainer>
			<Footer />
		</>
	)
})

export default Root
